package com.wayhome.srpingbootmybatis.policy.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.wayhome.srpingbootmybatis.config.ApiResult;
import com.wayhome.srpingbootmybatis.excelListener.PolicyDocListener;
import com.wayhome.srpingbootmybatis.mbs.expertimport.dto.SetlTldyExportDTO;
import com.wayhome.srpingbootmybatis.mbs.util.HeadContentCellStyle;
import com.wayhome.srpingbootmybatis.policy.bo.PolicyDocBO;
import com.wayhome.srpingbootmybatis.policy.dao.PolicyDocDao;
import com.wayhome.srpingbootmybatis.policy.dto.*;
import com.wayhome.srpingbootmybatis.policy.service.PolicyDocService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.WriterOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class PolicyDocServiceImpl implements PolicyDocService {

    @Resource
    private PolicyDocBO policyDocBO;

    @Resource
    private PolicyDocDao policyDocDao;

    @Override
    public ApiResult<Boolean> insertPolicyDoc(PolicyDocDTO policyDocDTO) throws Exception {

        return ApiResult.success(policyDocBO.insertPolicyDoc(policyDocDTO));
    }

    @Override
    public ApiResult<List<PolicyDocDTO>> queryList(ReqPolicyDocDTO reqPolicyDocDTO) throws Exception {
        return ApiResult.success(policyDocBO.queryList(reqPolicyDocDTO));
    }

    @Override
    public ApiResult<PolicyDocDTO> queryDocDetail(ReqPolicyDocDTO reqPolicyDocDTO) throws Exception {

        return ApiResult.success(policyDocBO.queryDocDetail(reqPolicyDocDTO));
    }

    @Override
    public ApiResult<Boolean> updateDoc(PolicyDocDTO policyDocDTO) throws Exception {
        return ApiResult.success(policyDocBO.updateDoc(policyDocDTO));
    }

    @Override
    public void importDocFile(MultipartFile file) throws Exception {
        PolicyDocListener policyDocListener = new PolicyDocListener(policyDocDao);
        InputStream inputStream = file.getInputStream();

        EasyExcel.read(inputStream, PolicyDocExcelDTO.class, policyDocListener).sheet().doRead();
        List<String> messageList = policyDocListener.getMessageList();

        File target = new File("/Users/liangcai/Desktop/tmp/" + file.getOriginalFilename());
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");// 设置字符编码
            String fileName = URLEncoder.encode("导入结果", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            try (FileOutputStream fos = new FileOutputStream(target)) {
                fos.write(file.getBytes());
            }
            EasyExcel.write(response.getOutputStream())
                    .withTemplate(target)
                    .sheet()
                    .doWrite(() -> {
                        List<List<String>> notes = new ArrayList<>();
                        notes.add(messageList);
                        return notes;
                    });
        }catch (Exception e) {
            log.info("导入政策文件发生错误：{}", e.getMessage(), e);
        } finally {
            FileUtils.forceDeleteOnExit(target);
        }

    }
    public static void transferToStream(MultipartFile file, OutputStream outputStream)
            throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }

    @Override
    public ApiResult<Boolean> uploadDocFile(ReqPolicyDocFileDTO request) throws Exception {

        return ApiResult.success(policyDocBO.saveUploadDocFile(request));
    }

    @Override
    public ApiResult<Boolean> deleteDoc(PolicyDocDTO policyDocDTO) throws Exception {
        return ApiResult.success(policyDocBO.deleteDoc(policyDocDTO));
    }

    @Override
    public void downloadPolicyFile(ReqPolicyDocDTO reqPolicyDocDTO) throws Exception {
        policyDocBO.downloadPolicyFile(reqPolicyDocDTO);
    }

}
